# -*- coding: utf-8 -*-
"""
Created on Tue Dec 20 10:06:11 2016

@author: yao.fu
"""
import os
import re
import subprocess

from AppGlobal import log_debug, AppGlobal
from Config import ConfigInfo

LOG_TAG = "AdbUtils"


def is_adb_set():
    config = ConfigInfo.getInstance()
    adb = config.getAdbPath()
    if adb is None or len(adb) <= 0 or not os.path.isfile(adb):
        return -100
    return 0


def adb_execute_device(serial, cmd):
    config = ConfigInfo.getInstance()
    adb = config.getAdbPath()
    if adb is None or len(adb) == 0:
        adb = "adb"

    if serial:
        command_text = str(adb + ' -s ' + serial + ' ' + cmd)
    else:
        command_text = str(adb + ' ' + cmd)
    log_debug(LOG_TAG, "++++++++++++++++++++++++++++++")
    log_debug(LOG_TAG, command_text)
    sub_p = subprocess.Popen(command_text, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    ret_b = sub_p.stdout.read()
    ret = None
    if ret_b is not None:
        ret = ret_b.decode()
    msg = None
    msg_b = sub_p.stderr.read()
    if msg_b is not None:
        msg = msg_b.decode('utf-8', "ignore")
    log_debug(LOG_TAG, "ret: " + ret)
    log_debug(LOG_TAG, "msg: " + msg)
    log_debug(LOG_TAG, "---------------------------------")
    return ret, msg


def adb_execute(cmd):
    serial = AppGlobal().get_device()
    if serial is None:
        return "", ""
    return adb_execute_device(serial, cmd)


def adb_execute_shell(cmd):
    command_text = str('shell ' + cmd)
    ret, msg = adb_execute(command_text)
    return ret, msg


def adb_get_devices():
    ret, msg = adb_execute_device(None, "devices -l")
    devices = ret.split(os.linesep)
    info_list = []
    for device in devices:
        if len(device) >= 0 and "device " in device:
            info = device.split("device ")
            serial = info[0].strip()
            info = info[1].strip()
            info = re.search(r'model:(.*) ', info, re.M | re.S | re.DOTALL)
            info_list.append({"serial": serial, "info": info.group(0).strip()})
    return info_list


def adb_forward(port, name):
    result, msg = adb_execute("forward tcp:" + str(port) + " localabstract:" + name)
    return result, msg


def adb_remove_forward(port):
    result, msg = adb_execute("forward --remove tcp:" + str(port))
    return result, msg


def adb_push(fro, to):
    result, msg = adb_execute("push " + fro + " " + to)
    return result, msg


def adb_get_prop(prop):
    ret, msg = adb_execute_shell("getprop " + prop)
    return ret.strip(), msg.strip()  # msg.replace(os.linesep, "")


def adb_chmod(permission, file_path):
    result, msg = adb_execute_shell("chmod " + str(permission) + " " + file_path)
    return result, msg


def adb_kill_pid(pid):
    result, msg = adb_execute_shell("kill " + str(pid))
    return result, msg


def adb_send_key_event(keycode):
    result, msg = adb_execute_shell("input keyevent " + str(keycode))
    return result, msg


def adb_send_text(text):
    result, msg = adb_execute_shell("input text " + str(text))
    return result, msg
